// 游戏常量
const CANVAS_WIDTH = 800;
const CANVAS_HEIGHT = 600;
const HEALTH_BAR_WIDTH = 200;
const HEALTH_BAR_HEIGHT = 20;
const ACTION_BAR_HEIGHT = 15;

class GameRenderer {
    constructor(canvas) {
        this.canvas = canvas;
        this.ctx = canvas.getContext('2d');
    }

    // 清空画布
    clear() {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }

    // 绘制进度条
    drawProgressBar(x, y, width, height, percentage, color) {
        this.ctx.fillStyle = '#333';
        this.ctx.fillRect(x, y, width, height);
        this.ctx.fillStyle = color;
        this.ctx.fillRect(x, y, width * percentage, height);
    }

    // 绘制文本
    drawText(text, x, y, fontSize = '16px', color = '#fff') {
        this.ctx.font = `${fontSize} Arial`;
        this.ctx.fillStyle = color;
        this.ctx.fillText(text, x, y);
    }

    // 绘制怪物
    drawMonster(monster) {
        // 绘制怪物形象（简单矩形表示）
        this.ctx.fillStyle = '#ff4444';
        this.ctx.fillRect(CANVAS_WIDTH/2 - 40, 100, 80, 80);

        // 绘制怪物血条
        const hpPercentage = monster.currentHp / monster.maxHp;
        this.drawProgressBar(
            CANVAS_WIDTH/2 - HEALTH_BAR_WIDTH/2,
            200,
            HEALTH_BAR_WIDTH,
            HEALTH_BAR_HEIGHT,
            hpPercentage,
            '#ff4444'
        );

        // 绘制怪物血量文本
        this.drawText(
            `HP: ${monster.currentHp}/${monster.maxHp}`,
            CANVAS_WIDTH/2 - 30,
            230
        );
    }

    // 绘制玩家
    drawPlayer(player) {
        // 绘制玩家形象（简单矩形表示）
        this.ctx.fillStyle = '#44aaff';
        this.ctx.fillRect(CANVAS_WIDTH/2 - 40, CANVAS_HEIGHT - 180, 80, 80);

        // 绘制玩家血条
        const hpPercentage = player.currentHp / player.maxHp;
        this.drawProgressBar(
            CANVAS_WIDTH/2 - HEALTH_BAR_WIDTH/2,
            CANVAS_HEIGHT - 80,
            HEALTH_BAR_WIDTH,
            HEALTH_BAR_HEIGHT,
            hpPercentage,
            '#44aaff'
        );

        // 绘制玩家蓝条
        const mpPercentage = player.currentMp / player.maxMp;
        this.drawProgressBar(
            CANVAS_WIDTH/2 - HEALTH_BAR_WIDTH/2,
            CANVAS_HEIGHT - 55,
            HEALTH_BAR_WIDTH,
            ACTION_BAR_HEIGHT,
            mpPercentage,
            '#4477ff'
        );

        // 绘制行动点进度条
        const apProgress = player.actionProgress / player.mobility;
        this.drawProgressBar(
            CANVAS_WIDTH/2 - HEALTH_BAR_WIDTH/2,
            CANVAS_HEIGHT - 35,
            HEALTH_BAR_WIDTH,
            ACTION_BAR_HEIGHT,
            apProgress,
            '#44ff44'
        );

        // 绘制状态文本
        this.drawText(
            `HP: ${player.currentHp}/${player.maxHp}`,
            CANVAS_WIDTH/2 - 100,
            CANVAS_HEIGHT - 90
        );
        this.drawText(
            `MP: ${player.currentMp}/${player.maxMp}`,
            CANVAS_WIDTH/2 + 20,
            CANVAS_HEIGHT - 90
        );
        this.drawText(
            `行动点: ${player.currentActionPoints}/${player.maxActionPoints}`,
            CANVAS_WIDTH/2 - 100,
            CANVAS_HEIGHT - 15
        );
        this.drawText(
            `防御状态: ${player.isDefending ? '是' : '否'}`,
            CANVAS_WIDTH/2 + 20,
            CANVAS_HEIGHT - 15
        );
    }

    // 绘制战斗日志
    drawBattleLog(battleLog) {
        this.ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
        this.ctx.fillRect(10, 10, 300, 150);
        
        battleLog.forEach((log, index) => {
            this.drawText(log, 20, 35 + index * 25, '14px', '#fff');
        });
    }
}

class Person {
    constructor(hp = 100, mp = 100, mobility = 10, actionPoints = 3, attack = 10, defense = 5) {
        // 基础属性初始化
        this.maxHp = hp          // 最大血量
        this.currentHp = hp      // 当前血量
        this.maxMp = mp          // 最大蓝量
        this.currentMp = mp      // 当前蓝量
        this.mobility = mobility  // 行动力
        this.maxActionPoints = actionPoints  // 最大行动点
        this.currentActionPoints = actionPoints  // 当前行动点
        this.attack = attack     // 攻击力
        this.defense = defense   // 防御力
        this.isDefending = false // 初始化为非防御状态
    }

    // 获取当前血量
    getHp() {
        return this.currentHp
    }

    // 设置血量
    setHp(value) {
        this.currentHp = Math.min(Math.max(0, value), this.maxHp)
    }

    // 获取当前蓝量
    getMp() {
        return this.currentMp
    }

    // 设置蓝量
    setMp(value) {
        this.currentMp = Math.min(Math.max(0, value), this.maxMp)
    }

    // 获取行动力
    getMobility() {
        return this.mobility
    }

    // 设置行动力
    setMobility(value) {
        this.mobility = Math.max(0, value)
    }

    // 获取当前行动点
    getActionPoints() {
        return this.currentActionPoints
    }

    // 设置行动点
    setActionPoints(value) {
        this.currentActionPoints = Math.min(Math.max(0, value), this.maxActionPoints)
    }

    // 重置行动点（比如回合开始时）
    resetActionPoints() {
        this.currentActionPoints = this.maxActionPoints
    }

    // 获取攻击力
    getAttack() {
        return this.attack
    }

    // 设置攻击力
    setAttack(value) {
        this.attack = Math.max(0, value)
    }

    // 获取防御力
    getDefense() {
        return this.defense
    }

    // 设置防御力
    setDefense(value) {
        this.defense = Math.max(0, value)
    }

    // 攻击目标
    attackTarget(target) {
        if (this.currentActionPoints < 1) {
            return false
        }

        this.currentActionPoints--
        let damage = this.attack
        if (target.isDefending) {
            damage = Math.max(0, damage - target.defense)
        }
        target.setHp(target.getHp() - damage)
        return true
    }

    // 进入防御状态
    defend() {
        if (this.currentActionPoints < 1) {
            return false
        }
        this.currentActionPoints--
        this.isDefending = true
        return true
    }

    // 累积行动点
    accumulateActionPoints() {
        this.actionProgress = (this.actionProgress || 0) + 1
        if (this.actionProgress >= this.mobility) {
            this.setActionPoints(this.currentActionPoints + 1)
            this.actionProgress = 0
        }
    }

    // 开始新回合
    startNewTurn() {
        this.isDefending = false
    }
}

class Monster {
    constructor(hp = 150, attack = 12, defense = 3, actionInterval = 10000) {
        this.maxHp = hp
        this.currentHp = hp
        this.attack = attack
        this.defense = defense
        this.actionInterval = actionInterval
        this.isDefending = false
    }

    getHp() { return this.currentHp }

    setHp(value) {
        this.currentHp = Math.min(Math.max(0, value), this.maxHp)
    }
}

class BattleScene {
    constructor(player, monster) {
        this.player = player;
        this.monster = monster;
        this.timeElapsed = 0;
        this.lastMonsterAttack = 0;
        this.battleLog = [];
        // 获取传入的canvas参数
        const canvas = document.getElementById('gameCanvas');
        this.renderer = new GameRenderer(canvas);
    }

    update(deltaTime) {
        this.timeElapsed += deltaTime

        this.player.accumulateActionPoints()

        if (this.timeElapsed - this.lastMonsterAttack >= this.monster.actionInterval) {
            this.monsterAttack()
            this.lastMonsterAttack = this.timeElapsed
        }

        this.updateUI()
    }

    monsterAttack() {
        let damage = this.monster.attack
        if (this.player.isDefending) {
            damage = Math.max(0, damage - this.player.getDefense())
        }
        this.player.setHp(this.player.getHp() - damage)
        this.addLog(`怪物攻击！${this.player.isDefending ? '玩家处于防御状态，' : ''}造成 ${damage} 点伤害`)
    }

    addLog(message) {
        this.battleLog.unshift(message)
        if (this.battleLog.length > 5) {
            this.battleLog.pop()
        }
        this.updateUI()
    }

    updateUI() {
        this.renderer.clear()
        this.renderer.drawMonster(this.monster)
        this.renderer.drawPlayer(this.player)
        this.renderer.drawBattleLog(this.battleLog)

        // 检查游戏是否结束
        if (this.player.getHp() <= 0 || this.monster.getHp() <= 0) {
            this.endBattle()
        }
    }

    endBattle() {
        clearInterval(gameInterval)
        const result = this.player.getHp() <= 0 ? "游戏结束 - 玩家死亡" : "游戏结束 - 怪物死亡"
        this.addLog(result)
        document.getElementById('controls').style.display = 'none'
    }
}

let battle
let gameInterval

function playerAttack() {
    if (battle.player.attackTarget(battle.monster)) {
        battle.addLog("玩家发动攻击！")
    } else {
        battle.addLog("行动点不足，无法攻击！")
    }
}

function playerDefend() {
    if (battle.player.defend()) {
        battle.addLog("玩家进入防御状态！")
    } else {
        battle.addLog("行动点不足，无法防御！")
    }
}

// 修改initGame函数
function initGame(ctx, canvas) {
    // 初始化游戏战斗
    const player = new Person(100, 100, 10, 3, 15, 8);
    const monster = new Monster(150, 12, 3, 10000);
    battle = new BattleScene(player, monster);
    
    // 启动游戏循环
    gameInterval = setInterval(() => {
        battle.update(100);
    }, 100);

    // 添加控制按钮
    const controls = document.createElement('div');
    controls.id = 'controls';
    controls.style.position = 'absolute';
    controls.style.bottom = '20px';
    controls.style.left = '50%';
    controls.style.transform = 'translateX(-50%)';
    controls.innerHTML = `
        <button class="menu-button" onclick="playerAttack()">攻击</button>
        <button class="menu-button" onclick="playerDefend()">防御</button>
    `;
    document.getElementById('gameInterface').appendChild(controls);
}
